<template>
  <div class="h-full w-full bg-black text-white overflow-hidden relative touch-none">
    <!-- 背景效果 -->
    <div class="absolute top-0 left-0 w-full h-full z-0 overflow-hidden pointer-events-none">
      <div class="gradient-orb top-left"></div>
      <div class="gradient-orb bottom-right"></div>
      <div class="grid-overlay"></div>
    </div>

    <!-- 主要内容区域 -->
    <div class="flex flex-col relative z-10 h-full">
      <div class="flex-1 flex flex-col px-6 pt-6 mx-auto w-full h-full max-h-screen relative">
        <!-- 进度条和返回按钮 -->
        <div class="flex items-center mb-8 gap-4">
          <button 
            class="border-none rounded-full w-8 h-8 flex items-center justify-center cursor-pointer transition-colors duration-200" 
            @click="navigation.handleBack"
          >
            <BackIcon :size="10" />
          </button>
          <div class="flex-1">
            <div class="h-4 bg-white/10 rounded overflow-hidden mr-10">
              <div class="progress-fill" :style="ui.progressStyle">
                <span class="text-xl pr-2 text-black">{{ ui.progressText }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 滚动内容区域 -->
        <div class="flex-1 overflow-y-auto custom-scrollbar w-full m-auto pb-28">
          <div class="flex-1 flex flex-col justify-between gap-8 will-change-transform pb-4 max-w-[800px] m-auto">
            <!-- 单词展示区域 -->
            <div class="text-center animate-fadeIn">
              <h1 class="text-5xl font-bold mb-2 bg-gradient-to-r from-[#4A99E9] to-[#5C2797] bg-clip-text text-transparent will-change-transform">
                {{ wordData.currentWord?.content || "..." }}
              </h1>
              <div class="flex items-center justify-center gap-2 mb-4">
                <button @click="speech.playPronunciation()" class="text-white/70 hover:text-white">
                  <EnglishPronunciationButton />
                </button>
                <div class="text-lg text-white/70">
                  {{ wordData.currentWord?.usphone ? `/${wordData.currentWord.usphone}/` : "" }}
                </div>
              </div>
              <div v-if="!ui.showDefinition" class="flex flex-col items-center gap-2 my-4">
                <div class="w-20 h-0.5 bg-white/30"></div>
                <div class="w-12 h-0.5 bg-white/30"></div>
              </div>
              <div v-else class="text-2xl text-white/90 my-4 animate-fadeIn">
                {{ wordData.currentWord?.definition || "" }}
              </div>
            </div>

            <div v-if="wordData.currentWord" class="flex-1 flex flex-col">
              <!-- 例句区域 -->
              <div 
                v-if="ui.showDefinition && wordData.currentWord?.example?.text"
                class="bg-white/5 rounded-lg p-6 mb-4 will-change-transform cursor-pointer" 
                @click="speech.playExampleSentence"
              >
                <p 
                  class="text-lg leading-relaxed mb-2" 
                  v-html="wordData.highlightedExample"
                ></p>
                <p class="text-base text-white/70 animate-fadeIn">
                  {{ wordData.currentWord.example.translation }}
                </p>
              </div>

              <!-- 相关单词区域 -->
              <div 
                v-if="ui.showDefinition && hasRelatedWords" 
                class="bg-white/5 rounded-lg p-6 animate-fadeIn will-change-transform"
              >
                <div class="flex flex-col gap-4">
                  <div 
                    v-for="(relatedWord, index) in displayedRelatedWords" 
                    :key="index" 
                    class="border-b border-white/10 pb-3 last:border-b-0 last:pb-0"
                  >
                    <div class="flex items-center gap-2 mb-1">
                      <span 
                        class="font-semibold text-[#4A99E9] cursor-pointer" 
                        @click="() => speech.playRelatedWord(relatedWord.word)"
                      >
                        {{ relatedWord.word }}
                      </span>
                      <span class="text-sm text-white/60">{{ relatedWord.partOfSpeech }}</span>
                    </div>
                    <div class="text-[0.95rem] text-white/80">{{ relatedWord.definition }}</div>
                  </div>
                </div>
                <div v-if="hasMoreRelatedWords" class="mt-4 text-center">
                  <button 
                    class="text-[#4A99E9] text-sm hover:underline"
                    @click="ui.showAllRelatedWords = !ui.showAllRelatedWords"
                  >
                    {{ ui.showAllRelatedWords ? '收起' : `显示全部 (${wordData.currentWord.relatedWords.length})` }}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部按钮区域 -->
        <div class="absolute bottom-0 left-0 right-0 flex justify-center py-6 px-6 z-20 w-full">
          <div class="w-full max-w-[800px] m-auto">
            <!-- 未显示释义时的按钮 -->
            <template v-if="wordData.currentWord && !ui.showDefinition">
              <div class="grid grid-cols-3 gap-4">
                <button 
                  class="py-4 border-none rounded-lg bg-green-600/30 text-white font-semibold text-lg transition-all duration-300 hover:bg-green-600/50" 
                  @click="wordLearning.handleResponse('know')"
                >
                  认识
                </button>
                <button 
                  class="py-4 border-none rounded-lg bg-yellow-600/30 text-white font-semibold text-lg transition-all duration-300 hover:bg-yellow-600/50" 
                  @click="wordLearning.handleResponse('fuzzy')"
                >
                  模糊
                </button>
                <button 
                  class="py-4 border-none rounded-lg bg-red-600/30 text-white font-semibold text-lg transition-all duration-300 hover:bg-red-600/50" 
                  @click="wordLearning.handleResponse('unknown')"
                >
                  不认识
                </button>
              </div>
            </template>
            
            <!-- 显示释义时的按钮 -->
            <template v-else-if="wordData.currentWord && ui.showDefinition">
              <div class="grid grid-cols-2 gap-4">
                <button 
                  class="py-4 border-none rounded-lg bg-blue-600/30 text-white font-semibold text-lg transition-all duration-300 hover:bg-blue-600/50" 
                  @click="wordLearning.handleNextWord"
                >
                  下一词
                </button>
                <button 
                  class="py-4 border-none rounded-lg bg-red-600/30 text-white font-semibold text-lg transition-all duration-300 hover:bg-red-600/50" 
                  @click="wordLearning.handleWrong"
                >
                  记错了
                </button>
              </div>
            </template>
            
            <!-- 学习完成时的按钮 -->
            <template v-else>
              <div class="grid grid-cols-1 gap-4">
                <button 
                  class="py-4 border-none rounded-lg bg-gradient-to-r from-blue-500 to-purple-800 text-white font-semibold text-lg transition-all duration-300 hover:opacity-90"
                  @click="navigation.generateEssay"
                >
                  生成AI文章
                </button>
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>
  </div>  
</template>

<script setup>
import { ref, computed, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useModalStore } from '@/stores/modal';
import BackIcon from '@/components/icons/BackIcon.vue';
import EnglishPronunciationButton from '@/components/icons/EnglishPronunciationButton.vue';

// ==================== 常量定义 ====================
const WORD_STATUS = {
  UNLEARNED: 0,
  KNOWN: 1,
  FUZZY: 2,
  UNKNOWN: 3
};

// ==================== 状态管理 ====================
const router = useRouter();
const route = useRoute();
const lessonId = computed(() => route.params.id || '未知课程');
const modalStore = useModalStore();

const wordData = reactive({
  knownQueue: [],
  learningQueue: [],
  currentWord: null,
  
  learningState: {
    totalWords: 0,
    learnedWords: 0,
    currentWordIndex: 0,
    totalVocabularyProgress: {
      totalLearnedWords: 0,
      totalWords: 0
    }
  },
  
  get highlightedExample() {
    const { example } = this.currentWord ?? {};
    if (!example?.text || !example?.highlight) return '';
    
    try {
      // 不区分大小写的替换
      const regex = new RegExp(example.highlight, 'i');
      return example.text.replace(
        regex, 
        match => `<span class='text-[#4A99E9] font-semibold'>${match}</span>`
      );
    } catch {
      return example.text;
    }
  },

  get progress() {
    const total = this.knownQueue.length + this.learningQueue.length;
    return total ? (this.knownQueue.length / total * 100) : 0;
  }
});

const ui = reactive({
  showDefinition: false,
  showAllRelatedWords: false,
  progressText: computed(() => `${Math.round(wordData.progress)}%`),
  progressStyle: computed(() => ({
    width: `${Math.round(wordData.progress)}%`
  }))
});

// ==================== 计算属性 ====================
const hasRelatedWords = computed(() => wordData.currentWord?.relatedWords?.length > 0);
const hasMoreRelatedWords = computed(() => 
  wordData.currentWord?.relatedWords?.length > 3
);
const displayedRelatedWords = computed(() => {
  if (!wordData.currentWord?.relatedWords) return [];
  return ui.showAllRelatedWords 
    ? wordData.currentWord.relatedWords 
    : wordData.currentWord.relatedWords.slice(0, 3);
});

// ==================== 工具函数 ====================

// 添加会话学习记录
const sessionProgress = reactive({
  learned: 0,
  needsSaving: false
});

// ==================== 语音模块 ====================
const speech = reactive({
  playPronunciation() {
    if (!wordData.currentWord?.content) return;
    
    // 自动播放发音
    const utterance = new SpeechSynthesisUtterance(wordData.currentWord.content);
    utterance.lang = 'en-US';
    
    const voices = window.speechSynthesis.getVoices();
    const preferredVoice = voices.find(v => v.lang.includes('en-US') && v.name.includes('Female')) ||
                          voices.find(v => v.lang.includes('en-US')) ||
                          voices.find(v => v.lang.includes('en'));
    
    if (preferredVoice) {
      utterance.voice = preferredVoice;
    }
    
    Object.assign(utterance, {
      volume: 1,
      rate: 0.9,
      pitch: 1
    });
    
    window.speechSynthesis.speak(utterance);
  },
  
  playExampleSentence() {
    this.playSpeech(wordData.currentWord?.example?.text);
  },
  
  playRelatedWord(word) {
    this.playSpeech(word);
  },
  
  playSpeech(text) {
    if (!text || !('speechSynthesis' in window)) return;

    const utterance = new SpeechSynthesisUtterance(text);
    utterance.lang = 'en-US';
    
    const voices = window.speechSynthesis.getVoices();
    const englishVoice = voices.find(voice => 
      voice.lang.includes('en') && voice.name.includes('Female')
    ) ?? voices.find(voice => voice.lang.includes('en'));
    
    if (englishVoice) {
      utterance.voice = englishVoice;
    }
    
    Object.assign(utterance, {
      volume: 1,
      rate: 0.9,
      pitch: 1
    });
    
    window.speechSynthesis.speak(utterance);
  }
});

// ==================== 导航模块 ====================
const navigation = reactive({
  handleBack() {
    if (sessionProgress.needsSaving) {
      // 保存进度逻辑
    }
    
    if (route.params.id && route.params.id.includes('-')) {
      const unitId = route.params.id.split('-')[0];
      router.push(`/reading?unit=${unitId}`);
    } else {
      router.push('/reading');
    }
  },
  
  generateEssay() {
    if (sessionProgress.needsSaving) {
      // 保存进度逻辑
    }
    
    if (route.params.id && route.params.id.includes('-')) {
      const unitId = route.params.id.split('-')[0];
      const essayId = `essay-unit-${unitId}`;
      router.push(`/reading/essay/${essayId}`);
    } else {
      router.push('/reading');
    }
  }
});

// ==================== 单词学习模块 ====================
const wordLearning = reactive({
  async loadWordData() {
    try {
      // 模拟API加载数据
      const mockData = {
        words: [
          {
            id: '1',
            content: 'parasite',
            usphone: 'pærəsaɪt',
            definition: 'n. 寄生虫，寄生动植物',
            example: {
              text: 'Many diseases are caused by parasites.',
              translation: '许多疾病都是由寄生虫引起的。',
              highlight: 'parasites'
            },
            relatedWords: [
              { word: 'parasitic', partOfSpeech: 'adj.', definition: '寄生的；由寄生虫引起的' },
              { word: 'parasitize', partOfSpeech: 'v.', definition: '寄生于；侵害；使寄生' }
            ],
            wordFamily: '派生'
          },
          {
            id: '2',
            content: 'abundant',
            usphone: 'əˈbʌndənt',
            definition: 'adj. 丰富的；充裕的；大量的',
            example: {
              text: 'The region has abundant natural resources.',
              translation: '该地区拥有丰富的自然资源。',
              highlight: 'abundant'
            },
            relatedWords: [
              { word: 'abundance', partOfSpeech: 'n.', definition: '丰富，充裕；大量' },
              { word: 'abundantly', partOfSpeech: 'adv.', definition: '丰富地；大量地' }
            ],
            wordFamily: '派生'
          },
          {
            id: '3',
            content: 'crucial',
            usphone: 'ˈkruːʃl',
            definition: 'adj. 关键的；决定性的；至关重要的',
            example: {
              text: 'Getting enough sleep is crucial for good health.',
              translation: '获得充足的睡眠对健康至关重要。',
              highlight: 'crucial'
            },
            relatedWords: [
              { word: 'crucially', partOfSpeech: 'adv.', definition: '至关重要地；决定性地' }
            ],
            wordFamily: '派生'
          }
        ]
      };
      
      // 设置学习队列
      wordData.learningQueue = mockData.words;
      wordData.knownQueue = [];
      
      // 设置学习状态
      wordData.learningState = {
        totalWords: mockData.words.length,
        learnedWords: 0,
        currentWordIndex: 0,
        totalVocabularyProgress: {
          totalLearnedWords: 0,
          totalWords: mockData.words.length
        }
      };
      
      // 设置当前单词
      this.setCurrentWord();
      
    } catch (error) {
      console.error('加载单词数据失败:', error);
    }
  },
  
  setCurrentWord() {
    if (wordData.learningQueue.length > 0) {
      wordData.currentWord = wordData.learningQueue[0];
      
      // 听力测试中，自动播放单词发音
      nextTick(() => {
        speech.playPronunciation();
      });
    } else {
      wordData.currentWord = null;
    }
    
    // 重置界面状态
    ui.showDefinition = false;
    ui.showAllRelatedWords = false;
  },
  
  handleResponse(responseType) {
    if (!wordData.currentWord) return;
    
    // 显示单词释义
    ui.showDefinition = true;
    
    // 根据用户反馈调整单词位置
    const currentWord = wordData.currentWord;
    
    if (responseType === 'know') {
      // 认识：移到已知队列
      wordData.knownQueue.push(currentWord);
      wordData.learningQueue.shift();
      sessionProgress.learned++;
      sessionProgress.needsSaving = true;
    } else if (responseType === 'fuzzy') {
      // 模糊：移到队列中间位置
      wordData.learningQueue.shift();
      const insertPosition = Math.min(6, wordData.learningQueue.length);
      wordData.learningQueue.splice(insertPosition, 0, currentWord);
    } else if (responseType === 'unknown') {
      // 不认识：移到队列前方位置
      wordData.learningQueue.shift();
      const insertPosition = Math.min(3, wordData.learningQueue.length);
      wordData.learningQueue.splice(insertPosition, 0, currentWord);
    }
  },
  
  handleNextWord() {
    this.setCurrentWord();
  },
  
  handleWrong() {
    if (!wordData.currentWord) return;
    
    // 如果用户点击"记错了"，将单词从已知队列移回到学习队列前方
    if (wordData.knownQueue.length > 0) {
      const lastKnownWord = wordData.knownQueue.pop();
      wordData.learningQueue.unshift(lastKnownWord);
      sessionProgress.learned--;
      sessionProgress.needsSaving = true;
    }
    
    this.setCurrentWord();
  }
});

// ==================== 生命周期钩子 ====================
onMounted(() => {
  if ('speechSynthesis' in window) {
    window.speechSynthesis.getVoices();
  }
  
  // 保存当前课程 ID 到 modalStore
  if (route.params.id) {
    modalStore.setLastCourse(route.params.id);
  }
  
  wordLearning.loadWordData();
});

onBeforeUnmount(() => {
  if ('speechSynthesis' in window) {
    window.speechSynthesis.cancel();
  }
});
</script>

<style scoped>
* {
  touch-action: pan-y;
}

/* 自定义滚动条样式 */
.custom-scrollbar {
  scrollbar-width: thin;
  scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
  -webkit-overflow-scrolling: touch; /* 增加iOS滚动支持 */
  overscroll-behavior: contain; /* 防止滚动穿透 */
}

.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: transparent;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

/* 确保内容区域不被底部按钮遮挡 */
.pb-28 {
  padding-bottom: 7rem !important;
}

/* 高亮例句中的单词 */
:deep(span.text-\[#4A99E9\]) {
  color: #4A99E9;
  font-weight: bold;
}

/* 背景效果 */
.gradient-orb {
  position: absolute;
  border-radius: 50%;
  filter: blur(70px);
  pointer-events: none;
}

.top-left {
  top: -10%;
  left: -10%;
  width: 45%;
  height: 45%;
  background: linear-gradient(135deg, rgba(74, 153, 233, 0.2) 0%, rgba(49, 89, 163, 0.07) 100%);
  animation: float 15s ease-in-out infinite alternate;
}

.bottom-right {
  bottom: -15%;
  right: -15%;
  width: 55%;
  height: 55%;
  background: linear-gradient(225deg, rgba(74, 153, 233, 0.15) 0%, rgba(92, 39, 151, 0.07) 100%);
  animation: float 20s ease-in-out infinite alternate-reverse;
}

.grid-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: 
      linear-gradient(to right, rgba(48, 51, 54, 0.08) 1px, transparent 1px),
      linear-gradient(to bottom, rgba(48, 51, 54, 0.08) 1px, transparent 1px);
  background-size: 25px 25px;
  opacity: 0.3;
  pointer-events: none;
}

@keyframes float {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(5%, 5%);
  }
}

.progress-fill {
  height: 100%;
  background: white;
  border-radius: 4rem;
  transition: width 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fadeIn {
  animation: fadeIn 0.3s ease-in-out;
}
</style> 